package com.wn.system.consumer;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wn.common.model.dto.bank.BankCardRequestDto;
import com.wn.system.entity.UserCard;
import com.wn.system.entity.UserDetail;
import com.wn.system.service.IUserCardService;
import com.wn.system.service.IUserDetailService;
import com.wn.system.service.impl.UserDetailServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author yellow Docter
 * @date 2023 -07-28
 * @desc
 */
@Component
@Slf4j
public class BankMsgConsumer {

    @Autowired
    private IUserDetailService userDetailService;

    @Autowired
    private IUserCardService userCardService;

    /**
     *  绑卡成功后的数据同步问题:
     *
     *  2、u_user_detail      表
     *         CARD_BIND_STATUS    绑卡状态
     *
     *  3、u_user_card    表
     *         BANK_NO              银行卡编号
     *         BANK_title           银行名称
     *         STATUS               状态
     *
     *   需要更新上面的数据
     *      银行系统会给  托管平台、用户 发送数  ( 拿到数据后就进行更新 )
     */

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "bank-queue"),
                    exchange = @Exchange(
                            name = "exchange-bank",
                            type = ExchangeTypes.DIRECT
                    ), //  bank.access.msg
                    key = "bank.access.msg"
            )
    )
    public void handlerBankMsg(@Payload BankCardRequestDto bankCardRequestDto){

        log.info("消息银行发送过来的消息:{}",bankCardRequestDto);

        //01  user_detail 表 绑卡的状态 修改

        //通过 userCode 拿到  UserDetail  进行修改
        userDetailService.update(Wrappers.lambdaUpdate(UserDetail.class)
                .set(UserDetail::getCardBindStatus,1)
                .eq(UserDetail::getUserCode,bankCardRequestDto.getUserCode())
        );

        UserDetail userDetail = userDetailService.getOne(Wrappers.lambdaQuery(UserDetail.class)
                .eq(UserDetail::getUserCode, bankCardRequestDto.getUserCode()));

        //02 user_card   表  绑卡后  银行编号、状态 的修改
        userCardService.update(
                Wrappers.lambdaUpdate(UserCard.class)
                        .set(UserCard::getBankNo,bankCardRequestDto.getBankNo())
                        .set(UserCard::getBankTitle,bankCardRequestDto.getBankTitle())
                        .set(UserCard::getStatus,1)
                        .eq(UserCard::getUserId,userDetail.getId())
        );

        log.info("消息银行发送过来的消息:绑卡状态进行同步...u_user_detail、u_user_card");
    }

}
